package com.xyauto.theme.vm

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import com.arialyy.annotations.Download
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.task.DownloadTask
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ZipUtils
import com.xyauto.theme.App
import com.xyauto.theme.BuildConfig
import com.xyauto.theme.Constant
import com.xyauto.theme.base.SingleLiveEvent
import com.xyauto.theme.bean.IThemeBean
import com.xyauto.theme.network.ApiCommon
import com.xyauto.theme.utils.AutoUtils
import com.xyauto.theme.utils.JieMainYiManager
import com.xyauto.theme.utils.ThemeFileManager
import kotlinx.coroutines.delay
import java.io.BufferedReader
import java.io.File
import java.io.FileReader

class MainListViewModel : BaseThemeModel() {


    val listData by lazy { SingleLiveEvent<MutableList<IThemeBean>>() }
    val nextData by lazy { SingleLiveEvent<Boolean>() }

    private var customerCode: String? = null

    fun getData(mType: String, pagerNumber: Int) {
        launch({
            customerCode = customerCode ?: loadFile("/system/armkeyword.bin")
            ApiCommon.commonService.getThemeList(
                mType.toInt(),
                ver = App.findLauncherVer(),
                customer_code = customerCode,
                is_three_screen = if (isSupportSplitWindow()) 1 else 2,
                page = pagerNumber,
                resolution = getResolution()
            )
        }, {
            nextData.value = it.data?.let { data -> data.page < data.page_next }
            it.data?.list?.let { list -> onPostValue(list) }
        }, isShowDialog = true)
    }


    /**
     * 系统度盘并选择使用的主题
     */
    fun onApply(context: Context, dataBean: IThemeBean?) {
        dataBean?.let { item ->
            launchNo({
                selectTheme(context, item)
            }, {
                if (!it) {
                    clearObserver.postValue(true)
                }
            })
        }
    }


    fun getLocalData() {
        launchNo({
            arrayListOf<IThemeBean>().apply {
                addAll(JieMainYiManager.findTheme())
                addAll(ThemeFileManager.scanThemeByPath(BuildConfig.DEFAULT_THEME_PATH))
                addAll(ThemeFileManager.scanThemeByPath(Constant.getSavePath(App.findLauncherVer())))
            }.sortedBy { it.getName() }
        }, {
            onPostValue(it)
        }, isShowDialog = true)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun registerBroadcast() {
        Aria.download(this).register()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun unregisterBroadcast() {
        Aria.download(this).unRegister()
    }

    @Download.onTaskComplete
    fun onTaskComplete(entity: DownloadTask?) {
        entity ?: return
        launchNo({
            entity.entity?.deleteData()
            entity.key.also {
                val filePath = entity.downloadEntity?.filePath ?: return@also
                if (!filePath.endsWith("zip") && !filePath.endsWith("rar")) {
                    delay(1000)
                    return@also
                }
                val file = File(filePath)
                val parentFile = file.parentFile ?: return@also

                ZipUtils.unzipFile(file, parentFile)
                file.delete()
            }
        }, {
            sendZipCompleteBroadcast(it)
        })
    }

    private fun sendZipCompleteBroadcast(url: String) {
        LogUtils.i(url)
        App.instance.sendBroadcast(Intent(Constant.ZIP_COMPLETE_BROADCAST).also {
            it.putExtra("url", url)
        })
    }

    private fun onPostValue(list: List<IThemeBean>) {
        listData.value = list.toMutableList()
    }


    private fun isSupportSplitWindow(): Boolean {
        val platform = Build.HARDWARE
        if (platform.isNullOrEmpty()) return false
        return platform.contains("qcom") || platform.contains("ac8257") || Build.VERSION.SDK_INT >= 30
    }


    /**
     * 1、横屏常规 2、横屏长条屏 3、大屏 4、竖屏常规 5、竖屏长条屏
     */
    private fun getResolution(): String = "${AutoUtils.displayWidth}x${AutoUtils.displayHeight}"


    private fun loadFile(path: String): String? {
        val file = File(path)
        if (!file.exists() || file.isDirectory) return null
        return BufferedReader(FileReader(file)).use {
            it.readText()
        }
    }
}